﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using DownloadMag.Core;

namespace DownloadMag.Protocols
{
    /// <summary>
    /// 下载协议服务提供商基类
    /// </summary>
    public class BaseProtocolProvider
    {
        static BaseProtocolProvider()
        {
            ServicePointManager.DefaultConnectionLimit = int.MaxValue;
        }

        protected WebRequest GetRequest(ResourceLocation location, ProxySettings proxy)
        {
            WebRequest request = WebRequest.Create(location.URL);
            request.Timeout = 30000;
            SetProxy(request, proxy);
            return request;
        }

        protected void SetProxy(WebRequest request, ProxySettings settings)
        {
            if (settings != null && settings.UseProxy)
            {
                WebProxy proxy = new WebProxy(settings.ProxyAddress, settings.ProxyPort);
                proxy.BypassProxyOnLocal = settings.ProxyByPassOnLocal;
                request.Proxy = proxy;

                if (!String.IsNullOrEmpty(settings.ProxyUserName))
                {
                    request.Proxy.Credentials = new NetworkCredential(
                        settings.ProxyUserName,
                        settings.ProxyPassword,
                        settings.ProxyDomain);
                }
            }
        }
    }
}
